package com.agileai.miscdp.hotweb.ui.actions.mastersub;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

import com.agileai.miscdp.DeveloperConst;
import com.agileai.miscdp.hotweb.database.DBManager;
import com.agileai.miscdp.hotweb.database.SqlBuilder;
import com.agileai.miscdp.hotweb.domain.Column;
import com.agileai.miscdp.hotweb.domain.ListTabColumn;
import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.hotweb.domain.mastersub.MasterSubFuncModel;
import com.agileai.miscdp.hotweb.domain.mastersub.SubTableConfig;
import com.agileai.miscdp.hotweb.ui.actions.BaseInitGridAction;
import com.agileai.miscdp.hotweb.ui.editors.mastersub.MSBasicConfigPage;
import com.agileai.miscdp.hotweb.ui.editors.mastersub.MSDetailJspCfgPage;
import com.agileai.miscdp.hotweb.ui.editors.mastersub.MasterSubModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.mastersub.MasterSubModelEditorContributor;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.StringUtil;
/**
 * 初始化表中功能模型数据
 */
public class MSInitGridAction extends BaseInitGridAction{
	private String tableName;
	private Text sqlText;
	private MSBasicConfigPage basicConfigPage;
	public MSInitGridAction() {
	}
	public void setContributor(MasterSubModelEditorContributor contributor) {
		this.contributor = contributor;
	}
	public void run() {
		IWorkbenchPage workbenchPage = contributor.getPage();
		IEditorPart editorPart = workbenchPage.getActiveEditor();
		modelEditor = (MasterSubModelEditor)editorPart;
		this.basicConfigPage = ((MasterSubModelEditor)modelEditor).getBasicConfigPage(); 
		Combo tableNameCombo = basicConfigPage.getTableNameCombo();
		String tableName = tableNameCombo.getText();
		Shell shell = modelEditor.getSite().getShell();

		String funcSubPkg = basicConfigPage.getFuncSubPkgText().getText();
		if (StringUtil.isNullOrEmpty(funcSubPkg)){
			DialogUtil.showMessage(shell,"消息提示","请填写目录编码!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		if (StringUtil.isNullOrEmpty(tableName)){
			DialogUtil.showMessage(shell,"消息提示","请选择主表!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		
		MasterSubFuncModel funcModel = ((MasterSubModelEditor)modelEditor).getFuncModel();
		if (funcModel.getSubTableConfigs().isEmpty()){
			DialogUtil.showMessage(shell,"消息提示","请至少选择一个子表!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		
		String projectName = modelEditor.getFuncModel().getProjectName();
		this.tableName = tableNameCombo.getText();
		String[] primaryKeys = DBManager.getInstance(projectName).getPrimaryKeys(tableName);
		if (primaryKeys == null ){
			MessageDialog.openInformation(shell, "消息提示","所选择的数据表没有主键!");
			return;
		}
		
		boolean doInitGrid = MessageDialog.openConfirm(shell,"消息提示","自动填写可能会覆盖已有内容，是否继续!");
		if (!doInitGrid){
			return;
		}
		sqlText = ((MasterSubModelEditor)modelEditor).getBasicConfigPage().getListSqlText();
        IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doRun(monitor);
				} catch (Exception e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
        };
        try {
			progressService.runInUI(PlatformUI.getWorkbench().getProgressService(),
					runnable,ResourcesPlugin.getWorkspace().getRoot());
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	@SuppressWarnings({"unchecked" })
	public void doRun(IProgressMonitor monitor) {
		monitor.beginTask("init grid values....", 1000);
		monitor.subTask("init basic values....");
		monitor.worked(50);
		((MasterSubModelEditor)modelEditor).buildFuncModel();
		MasterSubFuncModel funcModel = ((MasterSubModelEditor)modelEditor).getFuncModel();
		try {
			funcModel.setTableName(tableName);
			String namePrefix = MiscdpUtil.getValidName(tableName);
			String beanIdPrefix = namePrefix.substring(0,1).toLowerCase()+namePrefix.substring(1,namePrefix.length());
			String funcSubPkg = basicConfigPage.getFuncSubPkgText().getText();
			
			String funcBasePath = funcSubPkg;
			funcModel.setFuncSubPkg(funcSubPkg);
			funcModel.setListJspName(funcBasePath +"/"+namePrefix+"ManageList.jsp");
			funcModel.setDetailJspName(funcBasePath +"/"+namePrefix+"ManageEdit.jsp");
			String funcName = funcModel.getFuncName();
			funcModel.setListTitle(funcName);
			funcModel.setDetailTitle(funcName);
			funcModel.setServiceId(beanIdPrefix+"ManageService");
			
			ProjectConfig projectConfig = new ProjectConfig();
			String projectName = funcModel.getProjectName();
			String configFile = MiscdpUtil.getCfgFileName(projectName,DeveloperConst.PROJECT_CFG_NAME);
			projectConfig.setConfigFile(configFile);
			projectConfig.initConfig();
			String mainPkg = projectConfig.getMainPkg();
			funcModel.setImplClassName(mainPkg +".bizmoduler."+funcBasePath+"."+namePrefix +"ManageImpl");
			funcModel.setInterfaceName(mainPkg +".bizmoduler."+funcBasePath+"."+namePrefix+"Manage");
			
			DBManager dbManager = DBManager.getInstance(projectName);
			SqlBuilder sqlBuilder = new SqlBuilder();
			String[] colNames = MiscdpUtil.getColNames(dbManager, tableName);
            String listSql = sqlBuilder.findAllSql(tableName,colNames);
            listSql =  listSql + " where 1=1 ";
            funcModel.setListSql(listSql);
			String curListSql = listSql; 
            sqlText.setText(listSql);
        	int lastWhereIndex = curListSql.toLowerCase().indexOf("where");
        	if (lastWhereIndex > 0){
        		String lashWhere = curListSql.substring(lastWhereIndex,listSql.length());
        		List<String> params = MiscdpUtil.getParams(lashWhere);
        		MasterSubFuncModel.initPageParameters(params,funcModel.getPageParameters());
        	}
			
			funcModel.setExportCsv(true);
			funcModel.setExportXls(true);
			funcModel.setSortAble(true);
			funcModel.setPagination(true);

			monitor.subTask("init list grid values....");
			monitor.worked(300);
			Column[] columns = dbManager.getColumns(tableName);
			funcModel.getListTableColumns().clear();
			funcModel.getRsIdColumns().clear();
			initListTableColumns(columns, funcModel.getListTableColumns(),funcModel.getRsIdColumns(),null);
			funcModel.setTablePK(funcModel.getRsIdColumns().get(0));
			
			funcModel.getPageFormFields().clear();
			MasterSubFuncModel.initPageFormFields(columns,funcModel.getPageFormFields(),null);
			
			monitor.subTask("init form grid values....");
			monitor.worked(800);
			
			List<SubTableConfig> subTableConfigs = funcModel.getSubTableConfigs();
			for (int i=0;i < subTableConfigs.size();i++){
				SubTableConfig subTableConfig = subTableConfigs.get(i);
				String tableName = subTableConfig.getTableName();
				String foreignKey = subTableConfig.getForeignKey();
				columns = dbManager.getColumns(tableName);
				colNames = MiscdpUtil.getColNames(dbManager, tableName);
				String editMode = subTableConfig.getEditMode();
				String subTableId = subTableConfig.getSubTableId();
				subTableConfig.setTabTitile(tableName.toUpperCase());
				String sortField = subTableConfig.getSortField();
				String queryListSQL = sqlBuilder.findRecordsByForeignKeySql(tableName, colNames, foreignKey,funcModel.getTablePK(),sortField);
				subTableConfig.setQueryListSql(queryListSQL);
				
				if (SubTableConfig.ENTRY_EDIT_MODE.equals(editMode)){
					List<PageFormField> pageFormFields = funcModel.getSubEntryEditFormFields(subTableId);
					pageFormFields.clear();
					List<String> hiddenFields = new ArrayList<String>();
					hiddenFields.add(subTableConfig.getForeignKey());
					if (StringUtil.isNotNullNotEmpty(subTableConfig.getSortField())){
						hiddenFields.add(subTableConfig.getSortField());						
					}
					MasterSubFuncModel.initPageFormFields(columns, pageFormFields,hiddenFields);
					funcModel.putSubEntryEditFormFields(subTableId, pageFormFields);
				}
				else if (SubTableConfig.LIST_DETAIL_MODE.equals(editMode)){
					List<ListTabColumn> subListTableColumns = funcModel.getSubListTableColumns(subTableId);
					subListTableColumns.clear();
					this.initListTableColumns(columns, subListTableColumns, null, subTableConfig);
					funcModel.putSubListTableColumns(subTableId, subListTableColumns);
					
					List<PageFormField> pageFormFields = funcModel.getSubPboxFormFields(subTableId);
					pageFormFields.clear();
					List<String> hiddenFields = new ArrayList<String>();
					hiddenFields.add(subTableConfig.getForeignKey());
					if (StringUtil.isNotNullNotEmpty(subTableConfig.getSortField())){
						hiddenFields.add(subTableConfig.getSortField());						
					}
					MasterSubFuncModel.initPageFormFields(columns, pageFormFields,hiddenFields);
					funcModel.putSubPboxFormFields(subTableId, pageFormFields);
					
					String pboxNamePrefix = MiscdpUtil.getValidName(tableName);
					String pboxJspName = funcBasePath +"/"+pboxNamePrefix+"EditBox.jsp";
					subTableConfig.setPboxJspName(pboxJspName);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		modelEditor.initValues();
		
		monitor.subTask("refresh viewer....");
		monitor.worked(900);
		
		TableViewer paramTableViewer = ((MasterSubModelEditor)modelEditor).getListJspCfgPage().getPageParamTableViewer();
		paramTableViewer.setInput(funcModel.getPageParameters());
		paramTableViewer.refresh();
		
		TableViewer columnTableViewer = ((MasterSubModelEditor)modelEditor).getListJspCfgPage().getColumnTableViewer();
		columnTableViewer.setInput(funcModel.getListTableColumns());
		columnTableViewer.refresh();
		
		MSDetailJspCfgPage detailJspCfgPage = ((MasterSubModelEditor)modelEditor).getDetailJspCfgPage();
		TableViewer tableViewer = detailJspCfgPage.getTableViewer();
		tableViewer.setInput(funcModel.getPageFormFields());
		tableViewer.refresh();
		detailJspCfgPage.refreshSubTabConfig();
		return;
	}
	
	
	public void initListTableColumns(Column[] columns,List<ListTabColumn> listTableColumns,List<String> rsIdColumns,SubTableConfig subTableConfig){
		for (int i=0;i < columns.length;i++){
			if (columns[i].isPK()){
				if (rsIdColumns != null){
					rsIdColumns.add(columns[i].getName());					
				}
				else if (subTableConfig != null){
					subTableConfig.setPrimaryKey(columns[i].getName());
				}
				continue;
			}
			if (subTableConfig != null){
				if(columns[i].getName().equals(subTableConfig.getForeignKey())){
					continue;
				}
			}
			ListTabColumn listTabColumn = new ListTabColumn();
			listTabColumn.setProperty(columns[i].getName());
			listTabColumn.setTitle(columns[i].getLabel());
			listTabColumn.setWidth("100");
			listTabColumn.setCell(MiscdpUtil.getDataType(columns[i].getClassName()));
			if ("java.sql.Timestamp".equals(columns[i].getClassName())){
				listTabColumn.setFormat("yyyy-MM-dd HH:mm");				
			}
			else if ("java.sql.Date".equals(columns[i].getClassName())){
				listTabColumn.setFormat("yyyy-MM-dd");
			}
			listTableColumns.add(listTabColumn);				
		}
	}
}
